import {typeOf} from "@/units/tool";

/**
 * 创建URL参数
 * @param query
 * @param is_deep
 * @constructor
 */
export function CreatedUrlParams(query: { [key: string]: any }, is_deep: boolean = false) {
    let params: any[] = [];
    Object.entries(query).forEach(([key, value]) => {
        let type: string = typeOf(value)
        if (type === 'array') {
            for (let index in value) {
                params.push([`${key}[${index}]`, value[index]])
            }
        } else if (type === 'object') {
            for (let find in value) {
                const subtype: string = typeOf(value[find])
                if (subtype === 'number' || subtype === 'string') {
                    params.push([is_deep ? `[${key}][${find}]` : `${key}[${find}]`, value[find]])
                } else if (subtype === 'boolean') {
                    params.push([is_deep ? `[${key}][${find}]` : `${key}[${find}]`, value[find] ? 1 : 0])
                } else if (subtype === 'array') {
                    for (let index in value) {
                        params.push([is_deep ? `[${key}][${find}][${index}]` : `${key}[${find}][${index}]`, value[find] ? 1 : 0])
                    }
                } else if (subtype === 'object') {
                    for (let sort of CreatedUrlParams(value, true)) {
                        params.push([is_deep ? `[${key}][${find}]${sort[0]}` : `${key}[${find}]${sort[0]}`, sort[1]])
                    }
                }
            }
        } else if (type === 'number' || type === 'string') {
            params.push([is_deep ? `[${key}]` : `${key}`, value])
        } else if (type === 'boolean') {
            params.push([is_deep ? `[${key}]` : `${key}`, (value ? 1 : 0)])
        }
    });
    return params
}


/**
 * 创建URL
 * @param action
 * @param query
 * @constructor
 */
export function CreatedUrl(action: string, query: { [key: string]: any }): string {
    const params = CreatedUrlParams(query)
    const urlQuery = params.map(([key, value]) => `${key}=${value}`).join('&')
    return action + '?' + urlQuery
}